#include						"QtAsyncUdpSocket.h"

QtAsyncUdpSocket::QtAsyncUdpSocket() : ASocket(2)
{
	_buffer.init();
	_socket.bind(4243);
	_type = ASocket::UDP;
}

QtAsyncUdpSocket::~QtAsyncUdpSocket()
{
}

void							QtAsyncUdpSocket::init()
{
	connect(&_socket, SIGNAL(readyRead()), this, SLOT(handleRead()));
}

void							QtAsyncUdpSocket::close()
{
	_socket.close();
}

void							QtAsyncUdpSocket::connectToHost(const std::string &ip, const std::string &port)
{
	_socket.connectToHost(QString(ip.c_str()), QString(port.c_str()).toShort());
	std::cout << "Connected to Host " << ip << ":" << port << std::endl;
}

void							QtAsyncUdpSocket::sendPacket(Packet *packet, QHostAddress &ip, quint16 id)
{
	const char *				data = (const char *)packet->toUdpNetworkPacket();
	QByteArray					dt = QByteArray ( data , packet->size());

	_socket.writeDatagram(dt.data(), dt.size(), ip, id);
	delete data;
}

void							QtAsyncUdpSocket::sendPacket(Packet *packet)
{
	// NOT USED
	size_t						size = packet->size();

	_socket.write((const char *)packet->toUdpNetworkPacket(), size);
}

QHostAddress 					QtAsyncUdpSocket::getIp() const
{
	return _ip;
}

void							QtAsyncUdpSocket::handleRead()
{
	int							received = 0;

	while (_socket.hasPendingDatagrams())
	{
		quint16					senderPort;
		received = _socket.readDatagram((char *)_tmp_buf, 4096, &_ip, &senderPort);
		if (received > 0)
			_receiveUdp(received);
	}
}	

void							QtAsyncUdpSocket::_receiveUdp(size_t bytes_transferred)
{
		std::vector<byte>		*receipt = new std::vector<byte>;
		for (unsigned short cnt = 0; cnt < bytes_transferred; ++cnt)
			receipt->push_back(_tmp_buf[cnt]);
		_handler->harvest(this, receipt);
}